﻿using AutoMapper;
using IMES.Common.Domain.DurianModel;
using IMES.Common.Domain.KeepModel;
using IMES.Common.Domain.KeepModel.Process;
using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using Keep.API.Common.L.Dtos;
using MediatR;
using System.Reflection.PortableExecutable;
using System.Transactions;

namespace Keep.API.Appliction.Command.workSheetFile
{
	/// <summary>
	/// 新增工单
	/// </summary>
	public class workSheetCreateHandler : IRequestHandler<workSheetCreateCommon, Result>
	{
		private readonly IBaseRepositorys<workSheet> _workSheetReq;//工单
		private readonly IBaseRepositorys<TaskTable> _taskTableReq;//任务表
		private readonly IBaseRepositorys<Product> _productReq;//产品表
		private readonly IBaseRepositorys<ProcessRoute> _processRouteRep; //工艺路线表
		private readonly IBaseRepositorys<WorkingProcedure> _workingProcedureReq; //工艺工序表
		private readonly IBaseRepositorys<ProcessManagement> _processManagementRep;//工序表
		private readonly IMapper _mapper;
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="workSheetReq"></param>
		/// <param name="taskTableReq"></param>
		/// <param name="mapper"></param>
		public workSheetCreateHandler(IBaseRepositorys<workSheet> workSheetReq, IBaseRepositorys<TaskTable> taskTableReq, IBaseRepositorys<Product> productReq, IBaseRepositorys<ProcessRoute> processRouteRep, IBaseRepositorys<WorkingProcedure> workingProcedureReq, IBaseRepositorys<ProcessManagement> processManagementRep, IMapper mapper)
		{
			_workSheetReq = workSheetReq;
			_taskTableReq = taskTableReq;
			_productReq = productReq;
			_processRouteRep = processRouteRep;
			_workingProcedureReq = workingProcedureReq;
			_processManagementRep = processManagementRep;
			_mapper = mapper;
		}
		/// <summary>
		/// 新增工单
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<Result> Handle(workSheetCreateCommon request, CancellationToken cancellationToken)
		{

			var result = new Result() { Code = (int)CodeEnum.success, Messege = "新增工单成功" };
			var workSheetNumbersresult = "";
			try
			{
				// 保存工单信息

				var workSheets = _mapper.Map<workSheet>(request.WorkSheets);
				var produc= _productReq.GetAll().First(c=>c.ProductId == Convert.ToInt32(workSheets.ProductNumber));
				workSheets.ProductNumber  = produc.ProductNumber;
				var addwork = 0;
				if (request.WorkSheets.WorkSheetNumber == "")//如果工单编号为空，则自动生成工单编号
				{
					var newWorkSheetNumber = GetMaxProcessRouteNumber();
					workSheets.WorkSheetNumber = newWorkSheetNumber;
					addwork = _workSheetReq.Add(workSheets);
				}
				 

				string workSheetNumbers = workSheets.WorkSheetNumber;
				 
				if (addwork == 0)
				{
					throw new Exception("新增工单失败");
				}
				if (workSheetNumbers.Length >= 2)
				{
					// 现在可以安全地调用Substring，因为我们知道字符串至少有2个字符长
					workSheetNumbersresult = workSheetNumbers.Substring(0, 2);
				}
				foreach (var item in request.TaskTable)//添加任务表关联数据
				{
					item.WorkSheetNumber = workSheets.WorkSheetNumber;
				}
				var addtaks = _taskTableReq.AddRange(request.TaskTable);
				if (addtaks == null)
				{
					throw new Exception("新增工单失败");
				}
			}
			catch (Exception ex)
			{
				result.Code = (int)CodeEnum.error;
				result.Messege = ex.ToString();
				throw;
			}
			return result;

		}
		/// <summary>
		/// 获取最大流程编号
		/// </summary>
		/// <returns></returns>
		private string GetMaxProcessRouteNumber()
		{
			var query = _workSheetReq.GetAll();
			if (!query.Any())
			{
				// 如果集合为空，返回 GenerateId(1) 生成的ID
				return GenerateId(1);
			}
			else
			{
				// 如果集合不为空，获取最大的 WorkSheetId
				var maxId = query.Max(a => a.WorkSheetId);
				// 基于最大ID生成新的ID
				return GenerateId(maxId + 1);
			}
		}
		/// <summary>
		/// 前缀
		/// </summary>
		private static readonly string prefix = "GD";
		/// <summary>
		/// 生成流程编号
		/// </summary>
		/// <param name="counter"></param>
		/// <returns></returns>
		public static string GenerateId(int counter)
		{
			string datetimeStr = DateTime.Now.ToString("yyyyMMddHHmmss");
			string sequenceStr = counter.ToString("D5");
			string result = prefix + datetimeStr + "-" + sequenceStr;
			return result;
		}
	}

}
